<?php

/**
 * Class EventHandlesController
 *
 * @property WxActivitiesBotComponent $WxActivitiesBot
 */
class EventHandlesController extends AppController {

    var $name = 'EventHandles';
	var $autoRender = false;
	
	var $uses = array('EventHandle','EventLog','EventHandleLog','Order','Project','Task','Tasking','TaskExecute');
	
	var $components = array('WxActivitiesBot');
	
	public function beforeFilter(){
	    parent::beforeFilter();
	    $this->autoRender = false;
	}
	
    function admin_index() {
        $this->pageTitle = __('Event Handle', true);
    }
    
    /**
     * 
     * @param unknown $sp_event_id 指定重新处理的事件id，默认为0
     * @param unknown $force
     */
    function admin_bot($sp_event_id = 0,$force = false){
        
        $handle_name = 'bot';
        $event_handle = $this->EventHandle->find('first',array(
            'conditions'=>array(
                'handle_name' => $handle_name,
            ),
        ));
        $last_event_id = intval($event_handle['EventHandle']['last_event_id']);
         
        if(empty($event_handle)){
            $this->EventHandle->save(array('handle_name'=>$handle_name,'last_event_id'=>0));
            $event_handle['EventHandle']['last_event_id'] = 0;
            $event_handle['EventHandle']['id'] = $this->EventHandle->getLastInsertId();
        }
         
        if($sp_event_id){
            $events = $this->EventLog->find('all',array(
            				'conditions' => array(
            				    'id' => $sp_event_id,
            				    'model' => 'Order',
            				),
            				'order' => 'id asc',
            				'recursive' => -1,
            				'limit' => 100,
            ));
        }
        else{
            $events = $this->EventLog->find('all',array(
                'conditions' => array(
                    'id >' => $last_event_id,
                    'model' => 'Order',
                ),
                'order' => 'id asc',
                'recursive' => -1,
                'limit' => 100,
            ));
        }
        foreach($events as $event){
            $last_event_id = $event['EventLog']['id'];
            $last_handle_log = $this->EventHandleLog->find('first',array(
            				'conditions' => array(
            				    'handle_id' => $event_handle['EventHandle']['id'],
            				    'event_id' => $event['EventLog']['id'],
            				    'handle_name' => $handle_name,
            				),
            				'recursive' => -1,
            ));
        
            if(empty($last_handle_log)){
                $last_handle_log = array('EventHandleLog' => array('id'=>null,'times'=>0));
            }
            if(!$force && $last_handle_log['EventHandleLog']['status']){
                continue; // 每次都查询获取执行状态，对执行过的直接跳过，防止重复操作。
            }
            
            $before_data = json_decode($event['EventLog']['before_data'],true);
            $after_data = json_decode($event['EventLog']['after_data'],true);
        
            if($event['EventLog']['model'] == 'Order'){
                $order_id = $event['EventLog']['data_id'];
                
                if( $event['EventLog']['event'] == 'CREATE' ) { // 新项目创建
        
                    if( $after_data['status'] == -10 || $after_data['status']==1 && $after_data['model'] == "WxActivity" ) { //无需支付的订单
                        $this->WxActivitiesBot->sendActivityMsgByOrder( $order_id );
                        $this->EventHandleLog->save(array(
                            'id' => $last_handle_log['EventHandleLog']['id'],
                            'handle_name' => $handle_name,
                            'event_id' => $event['EventLog']['id'],
                            'handle_id' => $event_handle['EventHandle']['id'],
                            'status' => 1, //success
                            'times' => 1 + $last_handle_log['EventHandleLog']['times'],
                        ));
                    }
                }
                elseif($event['EventLog']['event'] == 'EDIT') {
                    if( $before_data['status']==0 && $after_data['status']==1 ) {
                        //订单已支付
                        $this->WxActivitiesBot->sendActivityMsgByOrder( $order_id );
                        $this->EventHandleLog->save(array(
                            'id' => $last_handle_log['EventHandleLog']['id'],
                            'handle_name' => $handle_name,
                            'event_id' => $event['EventLog']['id'],
                            'handle_id' => $event_handle['EventHandle']['id'],
                            'status' => 1, //success
                            'times' => 1 + $last_handle_log['EventHandleLog']['times'],
                        ));
                    }
                    elseif( $before_data['status']==1 && $after_data['status']==2 ) {
                        $this->WxActivitiesBot->sendDeliverMsgByOrder( $order_id );
                        $this->EventHandleLog->save(array(
                            'id' => $last_handle_log['EventHandleLog']['id'],
                            'handle_name' => $handle_name,
                            'event_id' => $event['EventLog']['id'],
                            'handle_id' => $event_handle['EventHandle']['id'],
                            'status' => 1, //success
                            'times' => 1 + $last_handle_log['EventHandleLog']['times'],
                        ));
                    }
                }
            }
        }
        if(!$sp_event_id){
            // 非特定事件处理时，更新最后已处理的事件id
            $this->EventHandle->updateAll(array('last_event_id'=>$last_event_id),array('id'=> $event_handle['EventHandle']['id']));
        }
        echo 'over';
    }
    
    /**
     * email事件处理器，
     * @param number $sp_event_id 默认为零，接着处理后续的事件。如果传入了指定的事件id主要是用于重复处理失败的事件，修正错误
     */
	function admin_email($sp_event_id = 0,$force = false) { //specify
    	
		App::uses('EmailUtility', 'Utility');
		$email_sender = new EmailUtility();
		$this->autoRender = false;
		
		$smtpoptions = array(
			'host' => Configure::read('EventHandle.smtp_host'),
			'port' => Configure::read('EventHandle.smtp_port'),
			'username' => Configure::read('EventHandle.smtp_username'),
			'password' => Configure::read('EventHandle.smtp_pwd'),
			'timeout' => 10,
			'tls' => Configure::read('EventHandle.smtp_tls') ? true : false,
		);
		 
		$handle_name = 'email';
    	$event_handle = $this->EventHandle->find('first',array(
    		'conditions'=>array(
    			'handle_name' => $handle_name,
    		),
    	));
    	$last_event_id = intval($event_handle['EventHandle']['last_event_id']); 
    	
    	if(empty($event_handle)){
    		$this->EventHandle->save(array('handle_name'=>$handle_name,'last_event_id'=>0));
    		$event_handle['EventHandle']['last_event_id'] = 0;
    		$event_handle['EventHandle']['id'] = $this->EventHandle->getLastInsertId();
    	}
    	
    	if($sp_event_id){
    		$events = $this->EventLog->find('all',array(
    				'conditions' => array(
    					'id' => $sp_event_id,
    				),
    				'order' => 'id asc',
    				'recursive' => -1,
    				'limit' => 100,
    		));
    	}
    	else{
	    	$events = $this->EventLog->find('all',array(
	    		'conditions' => array(
	    			'id >' => $last_event_id,
	    		),
	    		'order' => 'id asc',
	    		'recursive' => -1,
	    		'limit' => 100,
	    	));
    	}
    	foreach($events as $event){
    		
    		$last_handle_log = $this->EventHandleLog->find('first',array(
    				'conditions' => array(
    						'handle_id' => $event_handle['EventHandle']['id'],
    						'event_id' => $event['EventLog']['id'],
    						'handle_name' => $handle_name,
    				),
    				'recursive' => -1,
    		));
    		
    		if(empty($last_handle_log)){
    			$last_handle_log = array('EventHandleLog' => array('id'=>null,'times'=>0));
    		}
    		if(!$force && $last_handle_log['EventHandleLog']['status']){
    			continue; // 每次都查询获取执行状态，对执行过的直接跳过，防止重复操作。
    		}
    		
    		if($event['EventLog']['model'] == 'Project'){
    			// 项目发出后，提醒后台人员与客户进行联系。    			
    			if( $event['EventLog']['event'] == 'CREATE' ) { // 新项目创建
    				
    				$projectinfo = $this->Project->find('first',array(
    					'conditions' => array('Project.id'=>$event['EventLog']['data_id']),
    					'contain' => array('Customer','Contact','Uploadfile'),
    				));
    				
    					$email_options = array(
    							'to' => explode(';',Configure::read('Project.create_notify_email')),
    							'subject' => '[' . Configure::read('Site.title') . '] [' . __('New Project').'] '.$projectinfo['Project']['name'],
    							'template' => 'new_project',
    							'viewVars' => array('projectinfo'=>$projectinfo),
    					);
    					
    					if($email_sender->send($email_options,$smtpoptions)){
    						$this->EventHandleLog->save(array(
    							'id' => $last_handle_log['EventHandleLog']['id'],
    							'handle_name' => $handle_name,
    							'event_id' => $event['EventLog']['id'],
    							'handle_id' => $event_handle['EventHandle']['id'],
    							'status' => 1, //success
    							'times' => 1 + $last_handle_log['EventHandleLog']['times'],
    						));
    						// status 记录成功状态  event_handle_logs(id,handle_name,handle_id,event_id, status,updated,times)
    						CakeLog::info('New Project Email Success.'.Configure::read('Project.create_notify_email').' '.$projectinfo['Project']['id'].'  '.$projectinfo['Project']['name']);
    					}
    					else{
    						// status 记录失败状态 event_handle_logs,记录状态，时间，失败次数
    						$this->EventHandleLog->save(array(
    								'id' => $last_handle_log['EventHandleLog']['id'],
    								'handle_name' => $handle_name,
    								'event_id' => $event['EventLog']['id'],
    								'handle_id' => $event_handle['EventHandle']['id'],
    								'status' => 0, // failed
    								'times' => 1 + $last_handle_log['EventHandleLog']['times'],
    						));
    						CakeLog::error('New Project Email Error.'.$projectinfo['Project']['id'].'  '.$projectinfo['Project']['name']);
    					}
    			}
    			
    		}
    		elseif($event['EventLog']['model'] == 'Task'){
    			// 项目发出后，提醒后台人员与客户进行联系。
    			//print_r($event);
    			if($event['EventLog']['event'] == 'EDIT') {
    				
    				$task_id = $event['EventLog']['data_id'];
    				$taskinfo = $this->Task->find('first',array(
    						'conditions' => array('Task.id'=>$event['EventLog']['data_id']),
    						'recursive'=> -1,
    				));
    				
    				$before_data = json_decode($event['EventLog']['before_data'],true);
    				$after_data = json_decode($event['EventLog']['after_data'],true);
    				if($before_data['status'] == 0 && $after_data['status']==1) { //状态从0变成1，项目已选标完成。通知用户已中标
    					
    					$execute_uid = $after_data['execute_uid'];
    					$tasking_users = $this->Tasking->find('all',array(
    						'conditions' => array('task_id'=>$task_id),
    						'joins' => array(array('table'=>'users','alias'=>'User','type'=>'inner','conditions'=> array('Tasking.user_id=User.id'))),
    						'recursive'=> -1,
    						'fields' => array('Tasking.status','User.id','User.username','User.email'),
    					));
    					foreach($tasking_users as $user){
    						$email_options = array(
    								'to' => $user['User']['email'],
    								'subject' => '[' . Configure::read('Site.title') . '] ' . __('Failure to bid').' '.$taskinfo['Task']['name'],
    								'template' => 'tender_finished',
    								'viewVars' => array('taskinfo'=>$taskinfo,'user'=> $user,'execute_uid' => $execute_uid),
    						);
    						if($execute_uid == $user['User']['id']){
    							$email_options['subject'] = '[' . Configure::read('Site.title') . '] ' . __('Success to bid').' '.$taskinfo['Task']['name'];
    						}
    						if($email_sender->send($email_options,$smtpoptions)){
    							$this->EventHandleLog->save(array(
    									'id' => $last_handle_log['EventHandleLog']['id'],
    									'handle_name' => $handle_name,
    									'event_id' => $event['EventLog']['id'],
    									'handle_id' => $event_handle['EventHandle']['id'],
    									'status' => 1, //success
    									'times' => 1 + $last_handle_log['EventHandleLog']['times'],
    							));
    							// status 记录成功状态  event_handle_logs(id,handle_name,handle_id,event_id, status,updated,times)
    							CakeLog::info('Send task bid email success.  '.$user['User']['email'].' '.$taskinfo['Task']['id'].'  '.$taskinfo['Task']['name']);
    						}
    						else{
    							// status 记录失败状态 event_handle_logs,记录状态，时间，失败次数
    							$this->EventHandleLog->save(array(
    									'id' => $last_handle_log['EventHandleLog']['id'],
    									'handle_name' => $handle_name,
    									'event_id' => $event['EventLog']['id'],
    									'handle_id' => $event_handle['EventHandle']['id'],
    									'status' => 0, // failed
    									'times' => 1 + $last_handle_log['EventHandleLog']['times'],
    							));
    							CakeLog::error("Send task bid email error.\t".$user['User']['email'].' '.$taskinfo['Task']['id'].'  '.$taskinfo['Task']['name']);
    						}
    					}
    				}
    			}
    		}
    		else{ //event notify
    			
    			$modelClass = $event['EventLog']['model'] ;
    			$this->loadModel($modelClass);
    			
    			
    			if($event['EventLog']['event'] == 'CREATE' || $event['EventLog']['event'] == 'EDIT') {
    				$datainfo = $this->{$modelClass}->find('first',array(
    						'conditions' => array($modelClass.'.id'=>$event['EventLog']['data_id']),
    						'recursive'=> 2,
    				));    				
    			}
    			//多个通知的邮箱用分号隔开
    			$email_options = array(
    					'to' => explode(';',Configure::read('EventHandle.notify_emails')),
    					'subject' => '[' . Configure::read('Site.title') . '] ' . __($modelClass.' '.$event['EventLog']['event']),
    					'template' => 'email_events',
    					'viewVars' => array('datainfo' => $datainfo,'model'=> $modelClass,'event' => $event['EventLog']['event']),
    			);
    			if($email_sender->send($email_options,$smtpoptions)){
    				$this->EventHandleLog->save(array(
    						'id' => $last_handle_log['EventHandleLog']['id'],
    						'handle_name' => $handle_name,
    						'event_id' => $event['EventLog']['id'],
    						'handle_id' => $event_handle['EventHandle']['id'],
    						'status' => 1, //success
    						'times' => 1 + $last_handle_log['EventHandleLog']['times'],
    				));
    				echo "Send event notify email success.<BR>\n";
    				// status 记录成功状态  event_handle_logs(id,handle_name,handle_id,event_id, status,updated,times)
    				CakeLog::info('Send event notify email success.'."\t".var_export($event,true).var_export($smtpoptions,true).var_export($email_options,true));
    			}
    			else{
    				// status 记录失败状态 event_handle_logs,记录状态，时间，失败次数
    				$this->EventHandleLog->save(array(
    						'id' => $last_handle_log['EventHandleLog']['id'],
    						'handle_name' => $handle_name,
    						'event_id' => $event['EventLog']['id'],
    						'handle_id' => $event_handle['EventHandle']['id'],
    						'status' => 0, // failed
    						'times' => 1 + $last_handle_log['EventHandleLog']['times'],
    				));
    				CakeLog::error("Send event notify email error.\t".var_export($event,true).var_export($smtpoptions,true).var_export($email_options,true));
    			}
    		}
    	}
    	if(!$sp_event_id){
	    	// 非特定事件处理时，更新最后已处理的事件id
	    	
	    	$last_event_id = $event['EventLog']['id'];
	    	$this->EventHandle->updateAll(array('last_event_id'=>$last_event_id),array('id'=> $event_handle['EventHandle']['id']));
    	}
    	echo 'over';
    }
	
	
}
?>